package main

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"strings"
)

func main()  {
	context.Background()
	stopChan := make(chan os.Signal)
	signal.Notify(stopChan, os.Interrupt)
	mux := http.NewServeMux()
	fmt.Println(http.Dir("html"))
	mux.Handle("/html/", http.FileServer(http.Dir("")))
	//mux.Handle("/getFiles/", http.FileServer(http.Dir("")))
	mux.Handle("/clean", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()
		form:=r.Form
		fmt.Printf("%v\n%v\n",form,r.PostForm)
		os.RemoveAll("data")
		os.MkdirAll("data", os.ModePerm)
	}))
	mux.Handle("/getFileContent", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if err:=r.ParseForm();err!=nil {
			w.Write([]byte("[]"))
			return
		}
		_path:=r.Form.Get("path")
		_name:=r.Form.Get("name");
		path:=filepath.Join(_path,_name)
		con,err:=ioutil.ReadFile(path)
		if err!=nil{
			return
		}
		w.Header().Set("Content-Type","imaset ge/svg+xml")
		w.Write(con)
	}))
	mux.Handle("/getFiles", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if err:=r.ParseForm();err!=nil {
			w.Write([]byte("[]"))
			return
		}
		_path:=r.Form.Get("path")
		if _path==""{
			w.Write([]byte("[]"))
			return
		}
		buf:=bytes.Buffer{}
		buf.Write([]byte("["))
		rc:=strings.NewReplacer("\\","\\\\","\"","\\\"","\n","","\r","","\t","","\f","","\v","",)
		filepath.Walk(_path,func(path string, info os.FileInfo, err error) error{
			if filepath.Ext(path)==".svg"{
				name,err:=filepath.Rel(_path,path)
				if err!=nil{
					return nil
				}
				/*cont,err:=ioutil.ReadFile(path)
				if err!=nil{
					return nil
				}
				str:=string(cont)
				idx:=strings.Index(str,"<svg")
				if idx>0{
					str=str[idx:]
				}

				str=rc.Replace(str)
				name=rc.Replace(name)

				w.Write([]byte("{\"name\":\""+name+"\",\"content\":\""+str+"\"},"))
				*/
				buf.Write([]byte("\""+rc.Replace(name)+"\","))
			}
			return nil
		})
		buf.Truncate(buf.Len()-1)
		buf.Write([]byte("]"))
		w.Write(buf.Bytes())
	}))
	svr := &http.Server{Addr: ":8989", Handler: mux}
	if err := svr.ListenAndServe(); err != nil {
		log.Printf("listen:%s\n", err)
	}
	<-stopChan
	log.Println("shutting down server ...")
}
